package cn.tedu.rtc.mqtt.service.messagesender;

import cn.tedu.rtc.mqtt.model.CommonTopicResponse;
import cn.tedu.rtc.mqtt.service.gateway.IMqttMessageGateway;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 根据自己的业务逻辑封装好的消息发送类
 */
@Service
@Slf4j
public class MessageSenderServiceImpl implements IMessageSenderService {

    @Autowired
    private IMqttMessageGateway messageGateway;

    @Autowired
    private ObjectMapper mapper;

    public void publish(String topic, CommonTopicResponse response) {
        this.publish(topic, 1, response);
    }

    public void publish(String topic, int qos, CommonTopicResponse response) {
        try {
            log.info("send topic: {}, payload: {}", topic, response.toString());
            messageGateway.publish(topic, mapper.writeValueAsBytes(response), qos);
        } catch (JsonProcessingException e) {
            log.info("Failed to publish the message. {}", response.toString());
            e.printStackTrace();
        }
    }
}